package ua.kpi.ipsa.expert.api.net;

import java.rmi.*;
import java.util.*;

/**
 * 
 * @author doctorpro
 *
 */
public class UsersSupervisor extends Thread {
	
	//
	private static final int USERS_SUPERVISOR_SLEEP_TIME = 2_000;

	//
	private Map<String, DefaultUsersConsole> activeUsers;
	
	private UserConsoleManager consoleManager;
	
	/**
	 * 
	 * @param activeUsers
	 */
	public UsersSupervisor(
			Map<String, DefaultUsersConsole> activeUsers, UserConsoleManager consoleManager) {
		this.activeUsers = activeUsers;
		this.consoleManager = consoleManager;
	}
	
	/**
	 * 
	 */
	@Override
	public void run() {		
		System.out.println("Users supervisor thread started [OK]");
		
		while (true) {
			synchronized (activeUsers) {
				for (Iterator<String> i = activeUsers.keySet().iterator(); i.hasNext();) {
					DefaultUsersConsole c = activeUsers.get(i.next());
					boolean online = false;
					try {
						online = c.assertUserOnline();
					} catch (RemoteException e) {
//						e.printStackTrace();
					}
					
					if (!online) {
						// kick the user
						System.out.println("Releasing user " + c.getLogin());
						consoleManager.releaseConsole(c);
					}
				}
			}
			try {
				sleep(USERS_SUPERVISOR_SLEEP_TIME);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
